package xyz.xtt.asset.service.impl;

import static xyz.xtt.common.asset.AssertUtils.isNull;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.xtt.asset.constants.AssetCache;
import xyz.xtt.asset.constants.ErrorMessage;
import xyz.xtt.asset.service.IPopularityCalcService;
import xyz.xtt.asset.service.ITblAssetService;
import xyz.xtt.common.starter.cache.CacheManager;
import xyz.xtt.pay.api.dto.PayAttach;
import xyz.xtt.pay.client.response.TblPayOrderDto;

/**
 * 热度计算器
 * 
 * @author huqibo
 * @date 2025/03/05
 */
@Slf4j
@Service
public class IPopularityCalcServiceImpl implements IPopularityCalcService {
	@Autowired
	private ITblAssetService iTblAssetService;
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@Autowired
	private CacheManager cacheManager;

	@Override
	public boolean calc(TblPayOrderDto payOrderDto) {
		PayAttach payAttach = JSONUtil.toBean(payOrderDto.getBusinessAttach(), PayAttach.class);
		isNull(payAttach, ErrorMessage.PAY_ATTACH_ISNULL);
		String goodsId = payAttach.getGoodsId();
		if (StringUtils.isBlank(goodsId)) {
			log.info("IPopularityCalcService payOrder:{}", JSONUtil.toJsonStr(payOrderDto));
			return false;
		}
		Long assetId = payAttach.getAssetId();
		BigDecimal orderMoney = payOrderDto.getOrderMoney();
		BigDecimal newOrderMoney = orderMoney.setScale(0, RoundingMode.DOWN);
		Boolean assetPopularity = iTblAssetService.assetPopularity(goodsId, newOrderMoney);
		if (Objects.equals(assetPopularity, Boolean.TRUE)) {
			BoundHashOperations<String, String, Long> popularityBoundHashOperations = stringRedisTemplate.boundHashOps("nft:goods:popularity");
			Long increment = popularityBoundHashOperations.increment(goodsId, newOrderMoney.longValue());
			cacheManager.delete(AssetCache.TBL_ASSET, goodsId);
			if (Objects.nonNull(assetId)) {
				cacheManager.delete(AssetCache.TBL_ASSET_WITH_ID, String.valueOf(assetId));
			}
			log.info("IPopularityCalcService:{}", increment);
		}
		return assetPopularity;
	}

}
